package com.bdqn.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.crm.pojo.*;
import com.bdqn.crm.service.SysRightService;
import com.bdqn.crm.service.SysRoleService;
import com.bdqn.crm.service.SysUserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysRightService sysRightService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private String SHIRO_LOGIN_COUNT="shiro_login_count";

    @GetMapping(value = "common/lefter")
    public String logout(){
        return "common/lefter";
    }

    /**
     * 退出到登录页面
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();//shiro消除
        return "/login";
    }

    @RequestMapping("/main")
    public String main(){
        return "main";
    }

    @RequestMapping("/doLogin")
    public String doLogin(HttpSession session,Model model, HttpServletRequest request, String usrName, String usrPassword){
        System.out.println(usrName+","+usrPassword);
        try{
            usrPassword = sysUserService.encryptPassword(usrPassword);//封装前进行加密

            UsernamePasswordToken token = new UsernamePasswordToken(usrName,usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);  //认证登录

            //认证登录成功清空记录
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT+usrName);

            SysUser sysUser = (SysUser) subject.getPrincipal();//认证(登录)成功

            //获取权限
            SysRole role = sysUser.getRole();

            List<SysRight> rights = sysRightService.findRightsByRole(role);
            role.getRights().addAll(rights);
            if(sysUser !=null){
                request.getSession().setAttribute("loginUser",sysUser);
                return "redirect:/main";
            }
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("message","登录失败，密码或用户错误");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message","用户被禁用,登录失败");
            return "login";
        }catch (DisabledAccountException e){
            model.addAttribute("message","账号1小时内禁止登录");
            return "login";
        }
        return "login";
    }
    @RequestMapping(value = "/user/list")
    public String list(HttpSession session,Model model,@RequestParam(value = "usrName",required = false) String usrName,
                       @RequestParam(value = "roleId",required = false) Long roleId,
                       @RequestParam(value = "pageIndex",defaultValue = "1") int pageIndex){
//        //数据回显
//        model.addAttribute("usrName",usrName);
//        model.addAttribute("roleId",roleId);
        //获取角色集合数据
        List<SysRole> list = sysRoleService.findAllRoles();
        model.addAttribute("roles",list);

        //页面查询过来的条件通过SysUser封装
//        SysUser sysUser= new SysUser();
//        if(usrName!=null){
//            sysUser.setUsrName(usrName);
//        }
        PageBean<SysUser> pageBean = sysUserService.pages(usrName,roleId,pageIndex);
        model.addAttribute("userPager",pageBean);
//        //划分分页
//        Pagee<SysUser> pagee = new Pagee();
//        pagee.setTotalCount(sysUserService.getPageListTotal(sysUser));  //获取总记录数设置在分页中
//        pagee.setCurrPageNo(pageIndex);  //当前页
//        model.addAttribute("userPager",pagee);
//        //设置分页信息
//        List<SysUser> pageList = sysUserService.getPageList(sysUser,pagee);
//        model.addAttribute("user",pageList);
        return "user/list";
    }

    /**
     * 跳转添加页面
     * @param model
     * @return
     */
    @GetMapping(value = "/user/add")
    public String add(Model model){
        //获取角色集合数据
        List<SysRole> list1 = sysRoleService.findAllRoles();
        model.addAttribute("roles",list1);
        return "user/add";
    }

    @PostMapping(value = "user/save")
    public String save(SysUser sysUser, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        boolean flag =sysUserService.save(sysUser);
        if (flag ==true){
            out.print("<script>alert(\"添加成功!\")</script>");
        }else{
            out.print("<script>alert(\"添加失敗!\")</script>");
        }
        return "redirect:/user/list";
    }
    @RequestMapping(value = "user/edit")
    @RequiresPermissions(value = "用户编辑")
    public String edit(Model model,Long usrId){
        SysUser sysUser = sysUserService.getUser(usrId);
        List<SysRole> list1 = sysRoleService.findAllRoles();
        model.addAttribute("roles",list1);
        model.addAttribute("user",sysUser);
//        sysUserService.saveOrUpdate(sysUser);
        return "user/edit";
    }

    @ResponseBody
    @GetMapping("user/del/{usrId}")
    public Map del(Long usrId){
        Boolean a=sysUserService.deleSysUser(usrId);
//        String delResult ="{\"delResult\":\"+a\"}";
        Map map = new HashMap();
        map.put("delResult","true");
        return map;
    }
}
